// pages/supply-addgoods/supply-addgoods.js
import UploadImg from '../../util/uploadImg'
const uploadImg = new UploadImg()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    edit: false,
    index: '',
    Supply: {
      avatar: '',
      name: '',
      price: ''
    }
  },

  onLoad (options) {
    console.log(options)
    if (options.data) {
      this.setData({
        Supply: Object.assign({} ,this.data.Supply, JSON.parse(options.data)),
        edit: true,
        index: options.index
      })
    }
  },

  inputChange (evevt) {
    let key = `Supply.${evevt.currentTarget.dataset.type}`
    this.setData({
      [key]: evevt.detail
    })
  },

  chooseImage () {
    uploadImg.chooseImg(1,res => {
      this.setData({
        'Supply.avatar': res
      })
    })
  },

  removeImg (e) {
    this.setData({
      'Supply.avatar': ''
    })
  },

  back () {
    if (this.data.edit) {
      let pages = getCurrentPages()
      let prevPage = pages[pages.length - 2]
      let productList = prevPage.data.Supply.productList
      productList[this.data.index] = this.data.Supply
      prevPage.setData({
        'Supply.productList': productList
      })
    } else {
      let pages = getCurrentPages()
      let prevPage = pages[pages.length - 2]
      let productList = prevPage.data.Supply.productList
      productList.push(this.data.Supply)
      prevPage.setData({
        'Supply.productList': productList
      })
    }
    wx.navigateBack({
      delta: 1
    })
  },

  delete () {
    let pages = getCurrentPages()
    let prevPage = pages[pages.length - 2]
    let productList = prevPage.data.Supply.productList
    productList.splice(this.data.index, 1)
    prevPage.setData({
      'Supply.productList': productList
    })
    wx.navigateBack({
      delta: 1
    }) 
  }
})